import { storageSet, storageGet, isTauri, getTokenAsync } from './secure-storage';
import { API_BASE_URL } from '@/config/env';

export interface ImFriendship {
  owner_id: string;
  to_id: string;
  remark?: string;
  del_flag?: number;
  black?: number;
  create_time?: number;
  update_time?: number;
  sequence?: number;
  black_sequence?: number;
  add_source?: string;
  extra?: string;
  version?: number;
  user?: {
    id: number;
    snowflake_id?: number;
    open_id?: string;
    name: string;
    email: string;
    file_name?: string;
    abstract?: string;
    phone?: string;
    gender?: number;
  };
}

export interface ImFriendshipRequest {
  id: string;
  from_id: string;
  to_id: string;
  remark?: string;
  read_status?: number;
  add_source?: string;
  message?: string;
  approve_status?: number;
  create_time?: number;
  update_time?: number;
  sequence?: number;
  del_flag?: number;
  version?: number;
  user?: {
    id: number;
    snowflake_id?: number;
    open_id?: string;
    name: string;
    email: string;
    file_name?: string;
    abstract?: string;
    phone?: string;
    gender?: number;
  };
}

export interface AddFriendRequest {
  to_id: string;
  remark?: string;
  add_source?: string;
}

// 缓存键名
const FRIENDS_CACHE_KEY = 'friends_cache';
const FRIENDS_CACHE_TIMESTAMP_KEY = 'friends_cache_timestamp';

// 获取当前用户的 open_id（用于缓存键）
// 注意：前端统一使用 open_id 作为用户的唯一标识
const getCurrentUserId = (): string | null => {
  // 只使用 openId，不再使用 snowflakeId 或 userId
  return localStorage.getItem('openId');
};

// 异步获取当前用户的 open_id（用于 Tauri 环境，确保获取到最新的 open_id）
const getCurrentUserIdAsync = async (): Promise<string | null> => {
  if (isTauri()) {
    // Tauri 环境中，从安全存储获取 open_id
    try {
      const { storageGet } = await import('./secure-storage');
      const openId = await storageGet('openId');
      if (openId) return openId;
    } catch (e) {
      console.warn('从安全存储获取 open_id 失败，使用 localStorage:', e);
    }
  }
  // 回退到 localStorage
  return getCurrentUserId();
};

// 获取用户特定的缓存键
const getFriendsCacheKey = async (userId?: string | null): Promise<string> => {
  let uid = userId;
  if (!uid) {
    if (isTauri()) {
      uid = await getCurrentUserIdAsync();
    } else {
      uid = getCurrentUserId();
    }
  }
  return uid ? `${FRIENDS_CACHE_KEY}_${uid}` : FRIENDS_CACHE_KEY;
};

const getFriendsCacheTimestampKey = async (userId?: string | null): Promise<string> => {
  let uid = userId;
  if (!uid) {
    if (isTauri()) {
      uid = await getCurrentUserIdAsync();
    } else {
      uid = getCurrentUserId();
    }
  }
  return uid ? `${FRIENDS_CACHE_TIMESTAMP_KEY}_${uid}` : FRIENDS_CACHE_TIMESTAMP_KEY;
};

// 清除好友列表缓存（用于登录/登出时）
// 注意：只清除好友列表相关的缓存，不会影响聊天记录
export const clearFriendsCache = async (userId?: string | null): Promise<void> => {
  try {
    const { storageRemove } = await import('./secure-storage');
    const cacheKey = await getFriendsCacheKey(userId);
    const timestampKey = await getFriendsCacheTimestampKey(userId);
    
    // 只删除好友列表相关的键（friends_cache_* 和 friends_cache_timestamp_*）
    // 不会影响聊天记录（chat_messages_*）
    await storageRemove(cacheKey);
    await storageRemove(timestampKey);
    console.log('好友列表缓存已清除（不影响聊天记录）:', cacheKey, timestampKey);
  } catch (error) {
    console.error('清除好友列表缓存失败:', error);
  }
};

// 保存好友列表到缓存
export const saveFriendsToCache = async (friends: ImFriendship[]): Promise<void> => {
  try {
    const cacheKey = await getFriendsCacheKey();
    const timestampKey = await getFriendsCacheTimestampKey();
    const data = JSON.stringify(friends);
    const timestamp = Date.now().toString();
    
    await storageSet(cacheKey, data);
    await storageSet(timestampKey, timestamp);
    console.log('好友列表已保存到缓存:', friends.length, '个好友');
  } catch (error) {
    console.error('保存好友列表到缓存失败:', error);
  }
};

// 从缓存读取好友列表
export const loadFriendsFromCache = async (): Promise<ImFriendship[] | null> => {
  try {
    const cacheKey = await getFriendsCacheKey();
    const cached = await storageGet(cacheKey);
    if (cached) {
      const friends = JSON.parse(cached) as ImFriendship[];
      console.log('从缓存加载好友列表:', friends.length, '个好友');
      return friends;
    }
  } catch (error) {
    console.error('从缓存读取好友列表失败:', error);
  }
  return null;
};

// 更新缓存中的单个好友（用于增删改操作）
export const updateFriendInCache = async (
  action: 'add' | 'update' | 'remove',
  friend?: ImFriendship,
  to_id?: string
): Promise<void> => {
  try {
    const cached = await loadFriendsFromCache();
    if (!cached) return;

    let updated: ImFriendship[];
    switch (action) {
      case 'add':
        if (friend) {
          // 检查是否已存在
          const exists = cached.some(f => f.to_id === friend.to_id);
          if (!exists) {
            updated = [...cached, friend];
          } else {
            // 如果已存在，更新它
            updated = cached.map(f => f.to_id === friend.to_id ? friend : f);
          }
        } else {
          updated = cached;
        }
        break;
      case 'update':
        if (friend) {
          updated = cached.map(f => f.to_id === friend.to_id ? friend : f);
        } else {
          updated = cached;
        }
        break;
      case 'remove':
        if (to_id) {
          updated = cached.filter(f => f.to_id !== to_id);
        } else {
          updated = cached;
        }
        break;
      default:
        updated = cached;
    }

    await saveFriendsToCache(updated);
    console.log('缓存已更新:', action, friend?.to_id || to_id);
  } catch (error) {
    console.error('更新缓存失败:', error);
  }
};

// 从后端获取好友列表（并更新缓存）
export const getFriends = async (useCache: boolean = true): Promise<ImFriendship[]> => {
  // 如果使用缓存，先尝试从缓存读取
  if (useCache) {
    const cached = await loadFriendsFromCache();
    if (cached && cached.length > 0) {
      console.log('使用缓存的好友列表');
      // 异步从后端更新（不阻塞）
      fetchFriendsFromServer(false).catch(err => {
        console.error('后台更新好友列表失败:', err);
      });
      return cached;
    }
  }

  // 缓存为空时，加载所有好友数据（首次同步）
  return await fetchFriendsFromServer(false);
};

// 从服务器获取好友列表
// onlyToday: 如果为 true，只返回当天的数据（已废弃，现在总是加载所有好友）
const fetchFriendsFromServer = async (onlyToday: boolean = false): Promise<ImFriendship[]> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }

  const response = await fetch(`${API_BASE_URL}/api/im/friends`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取好友列表失败' }));
    throw new Error(error.message || '获取好友列表失败');
  }

  const data = await response.json();
  console.log('好友列表API返回的原始数据:', data);
  let friends = data.friends || [];
  
  // 如果只同步当天的数据，过滤掉历史很久的数据
  if (onlyToday) {
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    const todayStartTimestamp = todayStart.getTime();
    
    friends = friends.filter((friend: ImFriendship) => {
      // 使用 update_time 或 create_time，取较大的值（表示最近的活动时间）
      const lastActiveTime = Math.max(
        friend.update_time || 0,
        friend.create_time || 0
      );
      // 只保留今天的数据
      return lastActiveTime >= todayStartTimestamp;
    });
    
    console.log('只同步当天的好友数据，过滤后数量:', friends.length);
  }
  
  console.log('解析后的好友列表:', friends);
  console.log('好友数量:', friends.length);
  
  // 保存到缓存
  await saveFriendsToCache(friends);
  console.log('从服务器获取好友列表并更新缓存:', friends.length, '个好友');
  
  return friends;
};

export const addFriend = async (req: AddFriendRequest): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 先更新本地缓存（乐观更新）
  // 注意：这里只是发送请求，实际的好友关系需要对方同意后才能建立
  // 所以这里不更新缓存，等收到同意通知后再更新
  
  const response = await fetch(`${API_BASE_URL}/api/im/friends`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(req),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '添加好友失败' }));
    throw new Error(error.message || '添加好友失败');
  }
  
  // 添加成功后，重新从服务器获取最新列表并更新缓存
  await fetchFriendsFromServer();
};

export const removeFriend = async (to_id: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 先更新本地缓存（乐观更新）
  await updateFriendInCache('remove', undefined, to_id);
  
  const response = await fetch(`${API_BASE_URL}/api/im/friends/${encodeURIComponent(to_id)}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    // 如果后端删除失败，恢复缓存
    await fetchFriendsFromServer();
    const error = await response.json().catch(() => ({ message: '删除好友失败' }));
    throw new Error(error.message || '删除好友失败');
  }
  
  // 删除成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchFriendsFromServer();
};

export const updateFriendRemark = async (to_id: string, remark?: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  
  // 先更新本地缓存（乐观更新）
  const cached = await loadFriendsFromCache();
  if (cached) {
    const friend = cached.find(f => f.to_id === to_id);
    if (friend) {
      const updatedFriend = { ...friend, remark: remark || undefined };
      await updateFriendInCache('update', updatedFriend);
    }
  }
  
  const response = await fetch(`${API_BASE_URL}/api/im/friends/${encodeURIComponent(to_id)}/remark`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ remark: remark || null }),
  });

  if (!response.ok) {
    // 如果后端更新失败，恢复缓存
    await fetchFriendsFromServer();
    const error = await response.json().catch(() => ({ message: '更新备注失败' }));
    throw new Error(error.message || '更新备注失败');
  }
  
  // 更新成功后，重新从服务器获取最新列表并更新缓存（确保数据一致性）
  await fetchFriendsFromServer();
};

export const blackFriend = async (to_id: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/friends/${encodeURIComponent(to_id)}/black`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '拉黑好友失败' }));
    throw new Error(error.message || '拉黑好友失败');
  }
};

export const getFriendshipRequests = async (approve_status?: number): Promise<ImFriendshipRequest[]> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const params = new URLSearchParams();
  if (approve_status !== undefined) {
    params.append('approve_status', approve_status.toString());
  }

  const response = await fetch(`${API_BASE_URL}/api/im/friendship-requests?${params.toString()}`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取好友请求失败' }));
    throw new Error(error.message || '获取好友请求失败');
  }

  const data = await response.json();
  return data.requests || [];
};

export const createFriendshipRequest = async (request: ImFriendshipRequest): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/friendship-requests`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '创建好友请求失败' }));
    throw new Error(error.message || '创建好友请求失败');
  }
};

export const handleFriendshipRequest = async (request_id: string, approve_status: number): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/friendship-requests/${encodeURIComponent(request_id)}`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ approve_status }),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '处理好友请求失败' }));
    throw new Error(error.message || '处理好友请求失败');
  }
  
  // 如果同意了好友请求，重新从服务器获取最新好友列表并更新缓存
  if (approve_status === 1) {
    await fetchFriendsFromServer();
  }
};

